package com.chidopi.cdf.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.chidopi.market.aa.domain.UserDetailsImpl;

public class CdfAuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {
	private static Logger logger =
			LoggerFactory.getLogger(CdfAuthenticationSuccessHandler.class);
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
	    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
	    logger.debug("username=" + userDetails.getUsername());
	    session.setAttribute("username", userDetails.getUsername());
	    try {
	    	UserDetailsImpl user = (UserDetailsImpl) userDetails;
	    	session.setAttribute("user_id", user.getAccount().getId());
	    } catch (Exception e) {
	    	logger.warn("Cast UserDetails Error:", e);
	    }
		super.onAuthenticationSuccess(request, response, authentication);
	}
}
